package com.etime.shycourse.orde.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etime.shycourse.dao.NotifyDao;
import com.etime.shycourse.orde.dao.OrdersMapper;
import com.etime.shycourse.orde.pojo.Orders;
import com.etime.shycourse.orde.services.interfaces.CloseOrderTaskService;
import com.etime.shycourse.pojo.Notify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sound.midi.Soundbank;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 关闭订单定时任务service层实现类
 */
@Service
public class CloseOrderTaskServiceImpl implements CloseOrderTaskService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private NotifyDao notifyDao;

    /**
     * 系统自动关闭订单
     *
     * @return 修改了多少订单
     */
    @Override
    public int closeOrders() {
        List<Orders> list = selectClosedOrders ();
        int i = 0;
        if (list.size () > 0) {
            for (Orders order : list) {
                i += updateorders (order);
            }
        }
        if (i > 0) {
            Notify notify = new Notify ();
            notify.setCreatedtime (new Date ());
            notify.setPost ("超时关闭订单" + i + "个");
            notifyDao.insert (notify);
        }
        return i;
    }

    /**
     * 修改订单（关闭订单）
     *
     * @param orders
     * @return
     */
    private int updateorders(Orders orders) {
        //状态设置为关闭
        orders.setOrderstate (3);
        //关闭时间
        orders.setOrderclosetime (new Date ());
        //关闭说明
        orders.setOrderclosedesc ("订单超时关闭");
        //关闭人id=-1（统一设置为超级管理员）
        orders.setOrdercloseuserid (-1);
        orders.setOrderclosename ("超级管理员");
        orders.setOrderupdatetime (new Date ());
        int rtn = ordersMapper.updateById (orders);
        return rtn;
    }

    /**
     * 查询已过期订单
     * 条件：orderstate = 1
     * ordercreatetime+30min>=now()
     *
     * @return
     */
    private List<Orders> selectClosedOrders() {
        QueryWrapper<Orders> wrapper = new QueryWrapper<> ();
        wrapper.eq ("orderstate", 1);
        Calendar calendar = Calendar.getInstance ();
        calendar.add (Calendar.MINUTE, -30);
        wrapper.le ("ordercreatetime", calendar.getTime ());
        List<Orders> list = ordersMapper.selectList (wrapper);
        return list;
    }

}
